import { createRouter, createWebHistory } from "vue-router";
//验证token请求
import { verifyToken } from "@/api/getUser";
const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    name: "home",
    component: () => import("../page/Home/index.vue"),
    meta: { showList: true },
  },
  //登录
  {
    path: "/login",
    name: "login",
    component: () => import("@/page/Login/index.vue"),
    meta: { footerShow: false },
  },
  //注册
  {
    path: "/register",
    component: () => import("@/page/Register/index.vue"),
    meta: { footerShow: false },
  },
  //商品搜索
  {
    path: "/search/:keyword?",
    name: "search",
    component: () => import("@/page/Search/index.vue"),
  },
  //商品详情
  {
    path: "/detail",
    name: "detail",
    component: () => import("@/page/Detail/Detail.vue"),
  },

  //购物车
  {
    path: "/shopCart",
    name: "shopCart",
    component: () => import("@/page/ShopCart/ShopCart.vue"),
  },
  //支付
  {
    path: "/pay",
    name: "pay",
    component: () => import("@/page/Pay/Pay.vue"),
  },
  //支付成功
  {
    path: "/paySuccess",
    name: "paySuccess",
    component: () => import("@/page/PaySuccess/PaySuccess.vue"),
  },
  //填写核对订单信息
  {
    path: "/trade",
    name: "trade",
    component: () => import("@/page/Trade/Trade.vue"),
  },
  //订单信息页面
  {
    path: "/center",
    name: "center",
    component: () => import("@/page/Center/Center.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach(async (to, from, next) => {
  if (
    to.name === "pay" ||
    to.name === "paySuccess" ||
    to.name === "trade" ||
    to.name === "center"
  ) {
    let result: any = await verifyToken();
    if (result.code !== 200) {
      next({ name: "login" });
      alert("请先登录");
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
